import { createRouter, createWebHistory } from 'vue-router'
import axios from 'axios'
import store from './store'
import Home from './views/Home.vue'
import Login from './views/Login.vue'
import ColumnDetails from './views/ColumnDetails.vue'
import CreatePost from './views/CreatePost.vue'
import SignUp from './views/SignUp.vue'
import PostDetails from './views/PostDetails.vue'
import Assembly from './views/Assembly.vue'
import AssemblyDropdown from './components/Assembly/DropdownDetails.vue'
import AssemblyForm from './components/Assembly/FormDetails.vue'
import AssemblyLoading from './components/Assembly/LoadingDetails.vue'
import AssemblyAlert from './components/Assembly/AlertDetails.vue'
import AssemblyModal from './components/Assembly/ModalDetails.vue'
import AssemblyUpload from './components/Assembly/UploadDetails.vue'

const routerHistory = createWebHistory()
const router = createRouter({
  history: routerHistory,
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    }, {
      path: '/login',
      name: 'login',
      component: Login,
      meta: {
        redirectAlreadylogin: true
      }
    }, {
      path: '/sign',
      name: 'sign',
      component: SignUp
    }, {
      path: '/column/:id',
      name: 'column',
      component: ColumnDetails
    }, {
      path: '/create',
      name: 'create',
      component: CreatePost,
      meta: {
        requiredLogin: true
      }
    }, {
      path: '/post/:id',
      name: 'post',
      component: PostDetails
    }, {
      path: '/assembly',
      name: 'assembly',
      component: Assembly
    }, {
      path: '/assembly-dropdown',
      name: 'assembly-dropdown',
      component: AssemblyDropdown
    }, {
      path: '/assembly-form',
      name: 'assembly-form',
      component: AssemblyForm
    }, {
      path: '/assembly-loading',
      name: 'assembly-loading',
      component: AssemblyLoading
    }, {
      path: '/assembly-alert',
      name: 'assembly-alert',
      component: AssemblyAlert
    }, {
      path: '/assembly-modal',
      name: 'assembly-modal',
      component: AssemblyModal
    }, {
      path: '/assembly-upload',
      name: 'assembly-upload',
      component: AssemblyUpload
    }
  ]
})

router.beforeEach((to, from, next) => {
  const { user, token } = store.state
  const { redirectAlreadylogin, requiredLogin } = to.meta
  if (!user.isLogin) {
    if (token) {
      axios.defaults.headers.common.Authorization = `Bearer ${token}`
      store.dispatch('fetchCurrentUser').then(() => {
        if (redirectAlreadylogin) {
          next('/')
        } else {
          next()
        }
      }).catch((e) => {
        console.log(e)
        store.commit('loginOut')
        next('/login')
      })
    } else {
      if (requiredLogin) {
        next('/login')
      } else {
        next()
      }
    }
  } else {
    if (redirectAlreadylogin) {
      next('/')
    } else {
      next()
    }
  }
})

export default router
